import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Tag, message, Modal, Form, Input, Space, Row, Col, Descriptions } from 'antd';
import { CheckCircleOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { listTrainings, enrollTraining, getTrainingDetail } from '../../../api/training';

/**
 * 培训报名页面
 * 允许员工查看可报名的培训课程并进行报名
 */
const TrainingEnroll = () => {
    const [loading, setLoading] = useState(false);
    const [trainings, setTrainings] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [detailVisible, setDetailVisible] = useState(false);
    const [currentTraining, setCurrentTraining] = useState(null);
    const [enrollVisible, setEnrollVisible] = useState(false);
    const [enrollForm] = Form.useForm();
    const [detailLoading, setDetailLoading] = useState(false);

    useEffect(() => {
        fetchTrainings();
    }, [pagination.current, pagination.pageSize]);

    // 获取可报名的培训列表
    const fetchTrainings = async () => {
        setLoading(true);
        try {
            const response = await listTrainings({
                page: pagination.current,
                pageSize: pagination.pageSize,
                status: 'active',
            });
            
            setTrainings(response.data || []);
            setPagination({
                ...pagination,
                total: response.total || 0,
            });
        } catch (error) {
            console.error('获取培训列表失败:', error);
            message.error('获取培训列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 查看培训详情
    const handleViewDetail = async (record) => {
        setDetailLoading(true);
        try {
            const detail = await getTrainingDetail(record.id);
            setCurrentTraining(detail);
            setDetailVisible(true);
        } catch (error) {
            console.error('获取培训详情失败:', error);
            message.error('获取培训详情失败');
        } finally {
            setDetailLoading(false);
        }
    };

    // 打开报名表单
    const handleEnroll = (record) => {
        setCurrentTraining(record);
        setEnrollVisible(true);
        enrollForm.resetFields();
    };

    // 提交报名
    const handleEnrollSubmit = async () => {
        try {
            const values = await enrollForm.validateFields();
            
            setLoading(true);
            await enrollTraining({
                training_id: currentTraining.id,
                reason: values.reason || '',
                comment: values.comment || '',
            });
            
            message.success('报名成功');
            setEnrollVisible(false);
            fetchTrainings(); // 刷新培训列表
        } catch (error) {
            if (error.errorFields) {
                return; // 表单验证失败
            }
            console.error('报名失败:', error);
            message.error('报名失败: ' + (error.message || '未知错误'));
        } finally {
            setLoading(false);
        }
    };

    // 表格列配置
    const columns = [
        {
            title: '培训名称',
            dataIndex: 'title',
            key: 'title',
            render: (text, record) => (
                <a onClick={() => handleViewDetail(record)}>{text}</a>
            ),
        },
        {
            title: '培训类型',
            dataIndex: 'type',
            key: 'type',
            render: (type) => {
                const colorMap = {
                    '技能培训': 'blue',
                    '管理培训': 'purple',
                    '新员工培训': 'green',
                    '职业发展': 'orange',
                };
                return <Tag color={colorMap[type] || 'default'}>{type}</Tag>;
            },
        },
        {
            title: '开始日期',
            dataIndex: 'start_date',
            key: 'start_date',
        },
        {
            title: '结束日期',
            dataIndex: 'end_date',
            key: 'end_date',
        },
        {
            title: '培训人数',
            dataIndex: 'capacity',
            key: 'capacity',
            render: (capacity, record) => `${record.enrolled_count || 0}/${capacity}`,
        },
        {
            title: '报名截止日期',
            dataIndex: 'enrollment_deadline',
            key: 'enrollment_deadline',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="link" 
                        size="small" 
                        icon={<InfoCircleOutlined />}
                        onClick={() => handleViewDetail(record)}
                    >
                        详情
                    </Button>
                    <Button 
                        type="primary" 
                        size="small" 
                        icon={<CheckCircleOutlined />}
                        onClick={() => handleEnroll(record)}
                        disabled={record.is_enrolled || record.status === 'full'}
                    >
                        {record.is_enrolled ? '已报名' : '报名'}
                    </Button>
                </Space>
            ),
        },
    ];

    return (
        <>
            <Card title="培训报名">
                <Table
                    columns={columns}
                    dataSource={trainings}
                    rowKey="id"
                    loading={loading}
                    pagination={pagination}
                    onChange={(pagination) => setPagination(pagination)}
                />
            </Card>

            {/* 培训详情弹窗 */}
            <Modal
                title="培训详情"
                open={detailVisible}
                onCancel={() => setDetailVisible(false)}
                footer={[
                    <Button key="close" onClick={() => setDetailVisible(false)}>
                        关闭
                    </Button>,
                    <Button
                        key="enroll"
                        type="primary"
                        onClick={() => {
                            setDetailVisible(false);
                            handleEnroll(currentTraining);
                        }}
                        disabled={currentTraining?.is_enrolled || currentTraining?.status === 'full'}
                    >
                        {currentTraining?.is_enrolled ? '已报名' : '报名参加'}
                    </Button>,
                ]}
                width={700}
            >
                {detailLoading ? (
                    <div style={{ textAlign: 'center', padding: '20px' }}>加载中...</div>
                ) : currentTraining ? (
                    <>
                        <Descriptions bordered column={2}>
                            <Descriptions.Item label="培训名称" span={2}>{currentTraining.title}</Descriptions.Item>
                            <Descriptions.Item label="培训类型">{currentTraining.type}</Descriptions.Item>
                            <Descriptions.Item label="培训状态">
                                <Tag color={currentTraining.status === 'active' ? 'green' : 'orange'}>
                                    {currentTraining.status === 'active' ? '可报名' : '已满员'}
                                </Tag>
                            </Descriptions.Item>
                            <Descriptions.Item label="开始日期">{currentTraining.start_date}</Descriptions.Item>
                            <Descriptions.Item label="结束日期">{currentTraining.end_date}</Descriptions.Item>
                            <Descriptions.Item label="报名截止日期">{currentTraining.enrollment_deadline}</Descriptions.Item>
                            <Descriptions.Item label="培训人数">{`${currentTraining.enrolled_count || 0}/${currentTraining.capacity}`}</Descriptions.Item>
                            <Descriptions.Item label="培训讲师" span={2}>{currentTraining.instructor}</Descriptions.Item>
                            <Descriptions.Item label="培训地点" span={2}>{currentTraining.location}</Descriptions.Item>
                            <Descriptions.Item label="培训内容" span={2}>{currentTraining.description}</Descriptions.Item>
                        </Descriptions>
                    </>
                ) : null}
            </Modal>

            {/* 报名表单弹窗 */}
            <Modal
                title="培训报名"
                open={enrollVisible}
                onCancel={() => setEnrollVisible(false)}
                onOk={handleEnrollSubmit}
                confirmLoading={loading}
            >
                <Form
                    form={enrollForm}
                    layout="vertical"
                >
                    <Form.Item
                        label="培训名称"
                    >
                        <Input value={currentTraining?.title} disabled />
                    </Form.Item>
                    
                    <Form.Item
                        name="reason"
                        label="报名原因"
                        rules={[{ required: true, message: '请填写报名原因' }]}
                    >
                        <Input.TextArea rows={4} placeholder="请简要说明您报名参加的原因" />
                    </Form.Item>
                    
                    <Form.Item
                        name="comment"
                        label="其他备注"
                    >
                        <Input.TextArea rows={3} placeholder="其他需要说明的事项（可选）" />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default TrainingEnroll; 